package xyz.ibenben.zhongdian.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.HouseStatus;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.HouseStatusForm;
import xyz.ibenben.zhongdian.system.service.HouseStatusService;
import xyz.ibenben.zhongdian.system.service.PropertyOwnershipCertificateService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * 房屋状态控制类
 * 提供了一些基本的服务，如初始化、获取房屋状态列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("houseStatusForm")
@RequestMapping("/houseStatus")
public class HouseStatusController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "houseStatus";
    /**
     * 重定向页面2
     */
    private static final String REDIRECT2 = "redirect:/" + ENTITYNAME + "/getAll?ownerId=%s";

    @Resource
    private HouseStatusService houseStatusService;
    @Resource
    private PropertyOwnershipCertificateService propertyOwnershipCertificateService;

    /**
     * 初始化
     *
     * @param map             参数
     * @param houseStatusForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute HouseStatusForm houseStatusForm,
                     @RequestParam(value = "ownerId", required = false) Long ownerId, HttpSession session) {
        HouseStatusForm newHouseStatusForm = new HouseStatusForm();
        if (houseStatusForm != null) {
            newHouseStatusForm = houseStatusForm;
            if (ownerId != null) {
                newHouseStatusForm.setOwnerId(ownerId);
            }
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newHouseStatusForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newHouseStatusForm);
    }

    /**
     * 获取房屋状态列表
     *
     * @param map             参数
     * @param houseStatusForm 条件参数
     * @param ownerId         参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取房屋状态列表")
    public String getAll(Model map, @ModelAttribute HouseStatusForm houseStatusForm,
                         @RequestParam(value = "ownerId", required = false) Long ownerId) {
        if (ownerId != null) {
            houseStatusForm.setOwnerId(ownerId);
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), houseStatusForm);
        Page<HouseStatus> page = PageHelper.startPage(houseStatusForm.getPageIndex(), houseStatusForm.getPageSize());
        List<HouseStatus> list = houseStatusService.findAll(houseStatusForm);
        map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
        map.addAttribute(Constants.PI, page.toPageInfo());
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除房屋状态记录
     *
     * @param id              主键
     * @param request         请求
     * @param houseStatusForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除房屋状态记录")
    public String delete(@RequestParam("id") Long id, HttpServletRequest request,
                         @ModelAttribute HouseStatusForm houseStatusForm, SessionStatus status) {
        HouseStatus info = houseStatusService.selectByKey(id);
        houseStatusService.delete(info, request);
        if (houseStatusForm.getOwnerId() != null) {
            return String.format(REDIRECT2, houseStatusForm.getOwnerId());
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除房屋状态列表
     *
     * @param houseStatusForm 条件参数
     * @param request         请求
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除房屋状态列表")
    public String deleteAll(@ModelAttribute HouseStatusForm houseStatusForm,
                            HttpServletRequest request, SessionStatus status) {
        if (houseStatusForm.getSelectIds() != null) {
            String[] ids = houseStatusForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                HouseStatus info = houseStatusService.selectByKey(Long.parseLong(id));
                houseStatusService.delete(info, request);
            }
        }
        status.setComplete();
        if (houseStatusForm.getOwnerId() != null) {
            return String.format(REDIRECT2, houseStatusForm.getOwnerId());
        }
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开房屋状态添加页面
     *
     * @param map             参数
     * @param houseStatusForm 条件参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开房屋状态添加页面")
    public String openAddPage(Model map, @ModelAttribute HouseStatusForm houseStatusForm) {
        HouseStatus houseStatus = new HouseStatus();
        super.setPropertyOwnershipCertificate(map, houseStatusForm.getOwnerId(),
                houseStatus, propertyOwnershipCertificateService);
        map.addAttribute(ENTITYNAME, houseStatus);
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存房屋状态添加记录
     *
     * @param houseStatus   实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存房屋状态添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) HouseStatus houseStatus,
                                 BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            houseStatusService.save(houseStatus, request);
            if (houseStatus.isFromOwnerId()) {
                return String.format(REDIRECT2, houseStatus.getOwnerId());
            }
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 打开房屋状态修改页面
     *
     * @param map             参数
     * @param id              主键
     * @param houseStatusForm 条件参数
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开房屋状态修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute HouseStatusForm houseStatusForm) {
        HouseStatus info = houseStatusService.selectByKey(id);
        if (houseStatusForm.getOwnerId() != null) {
            info.setFromOwnerId(true);
        }
        map.addAttribute(ENTITYNAME, info);
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新房屋状态修改记录
     *
     * @param houseStatus   实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新房屋状态修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) HouseStatus houseStatus,
                                  BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            houseStatusService.updateNotNull(houseStatus, request);
            status.setComplete();
            if (houseStatus.isFromOwnerId()) {
                return String.format(REDIRECT2, houseStatus.getOwnerId());
            }
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 浏览房屋状态记录
     *
     * @param map             参数
     * @param id              主键
     * @param houseStatusForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览房屋状态记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute HouseStatusForm houseStatusForm) {
        map.addAttribute(ENTITYNAME, houseStatusService.selectByKey(id));
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

}

